package com.abe.libcore.base.screen

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.widget.Toast

abstract class AbeActivity : BScreenActivity() {
    private val appToast: Int = 0x999

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutRes())
        initContent()
    }

    protected abstract fun getLayoutRes(): Int

    protected abstract fun initContent()
    /**********************************************************************************************/
    protected fun getContext(): Context {
        return this
    }

    protected fun gotoActivity(act: Class<*>) {
        startActivity(getIntent(act))
    }

    protected fun gotoActivity(act: Class<*>, extras: Bundle) {
        val intent = getIntent(act)
        intent.putExtras(extras)
        startActivity(intent)
    }

    protected fun gotoActivityForResult(act: Class<*>, code: Int) {
        startActivityForResult(getIntent(act), code)
    }

    protected fun gotoActivityForResult(act: Class<*>, extras: Bundle, code: Int) {
        val intent = getIntent(act)
        intent.putExtras(extras)
        startActivityForResult(intent, code)
    }

    private fun getIntent(act: Class<*>): Intent {
        return Intent(this@AbeActivity, act)
    }

    /**********************************************************************************************/
    inner class BaseHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg?.what) {
                appToast -> Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show()
                else -> if (isImp(this@AbeActivity.javaClass, OnHandlerListener::class.java)) {
                    (this@AbeActivity as OnHandlerListener).dispatchHandleMessage(msg)
                }
            }
        }
    }

    protected fun toast(content: String) {
        if (TextUtils.isEmpty(content)) return
        localSendMsg(appToast, content)
    }

    protected fun localSendMsg(what: Int, obj: Any) {
        getHandler().sendMessage(getMessage(what, obj))
    }

    //获取Message
    private fun getMessage(what: Int, obj: Any): Message? {
        val msg = Message()
        msg.what = what
        msg.obj = obj
        return msg
    }

    //获取Handler
    protected fun getHandler(): BaseHandler {
        return BaseHandler(Looper.getMainLooper())
    }

    /**
     * 是否实现接口
     * @param a 类
     * @param b 接口
     */
    protected fun isImp(a: Class<*>, b: Class<*>): Boolean {
        return b.isAssignableFrom(a)
    }
}